package com.tian.intercptor;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * {@code @description:} 参数校验处理
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024/1/18 15:19
 * {@code @version:} 1.0
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class ParameterCheckInspect {

    @Resource
    private SpringValidatorAdapter springValidatorAdapter;

    @Before(value = "execution(public * com.tian.*.*(..))")
    public void before(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            Set<ConstraintViolation<Object>> violationSet = springValidatorAdapter.validate(arg);
            if (!violationSet.isEmpty()) {
                throw new ConstraintViolationException(violationSet.iterator().next().getMessage(), null);
            }
            return;
        }
    }
}